using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Xml;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ACM.cmsarea08;
using ACM.cmsarea08.Controls;
using ACM.cmsarea08.Administration;


namespace ACM.cmsarea08.Administration.Core {
	public partial class EditCategoria :  BaseEditPage {
		//protected itareanet.cmsarea08.Administration.Controls.MainButton adm_buttons;
		//protected ACM.cmsarea08.Administration.Controls.DropDownSezioni mio1;
		
		override protected void OnInit(EventArgs e)
		{
			if(ACM.cmsarea08.Users.CurrentUser.Role.Score>400)
				Response.Redirect("/loginadm.aspx?returnurl="+
								HttpUtility.UrlEncode(Request.ServerVariables["SCRIPT_NAME"].ToString()+
				                                        (Request.ServerVariables["QUERY_STRING"].ToString()==""?"":"?"+Request.ServerVariables["QUERY_STRING"].ToString()))
	);
			else if(ACM.cmsarea08.Users.CurrentUser.Role.Score>300)
				Response.Redirect("/administration/accessdeny.aspx");
			base.OnInit(e);
			InitializeComponent();
			
			
			
		}
		const string DBActionTable = "contenuti_manager";
		private string _ItemID;
		private string SezID;
		private string _Autore2ID;
		private string _AutoreID;
		private string datains = "-";
		private string Upd_Id = "-1";
		private string deleting = "0";
		private const string trad_query = "insert into {0} (titolo, descrizione, tipo, figliodi,data_mod,data_ins," +
			"attrib_param,thumb,lingua,edit_autore,tradotto_da,enabled,deleting) values " +
					"('{1}','{2}','C','{3}',Now(),Now(),'{4}','{5}','{6}','{7}','{8}','{9}','{10}')  ;";
		private const string insert_query = "insert into {0} (titolo, descrizione, tipo, figliodi, data_mod, data_ins, " +
			"attrib_param,thumb,lingua,edit_autore,upd_id,enabled,deleting,autore) " +
					"values ('{1}','{2}','C','{3}',Now(),{12},'{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}') ;";
		private const string update_query = "update {0} set edit_autore='{7}', titolo='{1}', descrizione='{2}',figliodi={3}, data_mod=Now(), " +
			"attrib_param='{4}', thumb='{5}', lingua='{6}', deleting='{9}' where id='{8}' limit 1 ;";
		public bool InsertMode {
			get {
				if(Request.QueryString["new"]==null)
					return false;
				else if( Request.QueryString["new"].ToString()=="1")
					return true;
				else
					return false;
			}
		}
		public bool TradMode {
			get {
				if(Request.QueryString["idt"]==null || Request.QueryString["idt"].ToString()=="0")
					return false;
				else if( Request.QueryString["new"].ToString()=="1")
					return true;
				else
					return false;
			}
		}
		public bool ConfirmChanges {
			get {
				if(Request.QueryString["conf"]==null)
					return false;
				else if( Request.QueryString["conf"].ToString()=="1")
					return true;
				else
					return false;
			}
		}
		protected bool RevMode{
			get {
				return ACM.cmsarea08.mainconfiguration.MainConf.RevMode;
			}
			set {
				ACM.cmsarea08.mainconfiguration.MainConf.RevMode=value;
			}
		}
		protected bool IsPublisher {
			get {
//				if(ViewState[ACM.cmsarea08.Users.CurrentUser.IdUtente + "_isPub"]==null){
//					bool ispub = ACM.cmsarea08.Users.CurrentUser.isRuolo("Publisher");
//					ViewState[ACM.cmsarea08.Users.CurrentUser.IdUtente + "_isPub"] = ispub;
//					return ispub;
//				}
//				else
//					return (bool)ViewState[ACM.cmsarea08.Users.CurrentUser.IdUtente + "_isPub"];
				return ACM.cmsarea08.Users.CurrentUser.Role.isPublisher;
			}
			
		}
//		public string ItemID {
//				get { return _ItemID;				}
//				set { _ItemID = value; }
//			}
		
		protected DBClass dclass = new DBClass();
		private void InitializeComponent()
		{
//			if(this.Master is itareanet.cmsarea08.Administration.Core.ListerPrivate) {
//
//			}
			_ItemID = getValidContentIDF();
			string smallForm = "";
			bool applysmart = true;
			//if( ACM.cmsarea08.Users.CurrentUser.isRuolo("SysAdm") || ACM.cmsarea08.Users.CurrentUser.isRuolo("Admin") )
				applysmart=false;
			/*if(applysmart && ACM.cmsarea08.Users.CurrentUser.isRuolo("Content Manager")) 
				smallForm="smart";
			if(applysmart && ACM.cmsarea08.Users.CurrentUser.isRuolo("DataEnter")) 
				smallForm="smart";*/
			if(adm_buttons!=null) {
				if(Request.Params["idi"]!=null)
				adm_buttons.StandardForm = false;
				NonStandardForm nsfOggettoForm = new NonStandardForm();
				if(TradMode){
					nsfOggettoForm.Titolo = rm.GetString("trans_catH");
					}else
					nsfOggettoForm.Titolo = (this.InsertMode?
				                         rm.GetString("new_catH"):
				                         rm.GetString("upd_catH"));
				nsfOggettoForm.FormName = "edit_cat" + smallForm;
				nsfOggettoForm.XmlPath = "/administration/edit_form/edit_cat";
				//opzionale:
				nsfOggettoForm.XslPath = "";
				if(Request.Params["idi"]!=null) 
					nsfOggettoForm.InstanceID = Request.Params["idi"].ToString();
				if(Request.Params["idc"]!=null) 
					nsfOggettoForm.ComponentID = Request.Params["idc"].ToString();				
				/* questo blocco va impostato solo se siamo in MODIFICA, previa query a DB */
				nsfOggettoForm.DbTable = "contenuti_manager"; // un sieabbi a nianti
				nsfOggettoForm.KeyField = "id"; // un sieabbi a nianti
				//pezzo lettura params da db - se update
				nsfOggettoForm.FormData = null;
				datains = "-";
				string datamod = "-";
				string autore = "-";
				string autore2 = "-";
				string footer = rm.GetString("created_by") + ": <b>{0}</b> | " + rm.GetString("data_ins") + ": <b>{1}</b>";
				string footer_ext = "<br/>" + rm.GetString("edited_by") + ": <b>{0}</b> | " + rm.GetString("data_mod") + ": <b>{1}</b>";
				string xmlstring = "";
				
				if(!InsertMode || TradMode){
					string query = "";
					
					if(!InsertMode){
						_ItemID = getValidContentIDF();
						query = "select id, titolo, lingua, descrizione, figliodi, data_mod, data_ins, attrib_param, " +
							"(select username from " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + 
							"utenti as ute where ute.id=autore) as autorename," +
							"(select username from " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + 
							"utenti as ute where ute.id=edit_autore) as autorename2," +
								"thumb as thumbimg, upd_id, deleting,autore,edit_autore from " +
					                                   ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable + 
							" where id='" + _ItemID +"' limit 1 ;";}
					else{
						_ItemID = Request.QueryString["idt"]!=null?Request.QueryString["idt"].ToString():"0";
						query = "select id, titolo, lingua, descrizione, figliodi, data_mod, data_ins, attrib_param, " +
							"(select username from " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + 
							"utenti as ute where ute.id=autore) as autorename," +
							"(select username from " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + 
							"utenti as ute where ute.id=edit_autore) as autorename2," +
							"thumb as thumbimg, upd_id, deleting,autore,edit_autore from " +
					                                   ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable + 
					                                   " where id='" + _ItemID +"' limit 1 ;";
					}
					DataSet ds = dclass.Helper_Dataset(query);
//					Response.Write("select id, titolo, data_mod, data_ins from " +
//					                                   itareanet.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable + 
//					                                   " where id='" + _ItemID +"' limit 1 ;");
					if(ds!=null){
						datains = ((DateTime)ds.Tables[0].Rows[0]["data_ins"]).ToString("yyyy-MM-dd hh:mm:ss");
						datamod = ((DateTime)ds.Tables[0].Rows[0]["data_mod"]).ToString("yyyy-MM-dd hh:mm:ss");
						autore = ds.Tables[0].Rows[0]["autorename"].ToString();
						autore2 = ds.Tables[0].Rows[0]["autorename2"].ToString();
						_Autore2ID = ds.Tables[0].Rows[0]["edit_autore"].ToString();
						_AutoreID = ds.Tables[0].Rows[0]["autore"].ToString();
						deleting = ds.Tables[0].Rows[0]["deleting"].ToString();
						SezID = ds.Tables[0].Rows[0]["figliodi"].ToString();
						Upd_Id = ds.Tables[0].Rows[0]["upd_id"].ToString();
					}else{
						goto esci;
					}
						
					
					
					
					FormDataAdapter fda = new FormDataAdapter();
					
					if(ds.Tables[0].Rows[0]["attrib_param"].ToString().Trim()!=""){
					string xmltemp = System.Text.Encoding.UTF8.GetString((byte[])ds.Tables[0].Rows[0]["attrib_param"]);
					string data = fda.Decompress(xmltemp);
					
				//	HttpContext.Current.Response.Write("#"+ data +"#"+ xmltemp + "#<hr>");
					if(data!=null && data!=string.Empty){
					if(fda.ValidateParamsXml(data)){
							
						//Response.Write("parametri trovati<br>" + HttpUtility.HtmlEncode(fda.ObjectToItanData(ds.Tables[0].Rows[0]["attrib_param"])));
						//	return;
						
						XmlDocument xdoc = fda.ItanDataToXmlDocument(data);
						if(xdoc!=null) {
							XmlNode nodes;
							nodes = xdoc.DocumentElement;
							//HttpContext.Current.Response.Write(HttpUtility.HtmlEncode(xdoc.InnerXml));
							XmlNode node = nodes.SelectSingleNode(("//attrib/param[pnome=\"showtitlecat\"]"));
							if(node!=null){
								ds.Tables[0].Columns.Add("showtitlecat");
								ds.Tables[0].Rows[0]["showtitlecat"] = node.ChildNodes[1].InnerText;
							}
							node = null;
							
							node = nodes.SelectSingleNode(("//attrib/param[pnome=\"showdesccat\"]"));
							if(node!=null){
								ds.Tables[0].Columns.Add("showdesccat");
								ds.Tables[0].Rows[0]["showdesccat"] = node.ChildNodes[1].InnerText;
							}
							
							node = null;
							node = nodes.SelectSingleNode(("//attrib/param[pnome=\"showartcat\"]"));
							if(node!=null){
								ds.Tables[0].Columns.Add("showartcat");
								ds.Tables[0].Rows[0]["showartcat"] = node.ChildNodes[1].InnerText;
							}
							node = null;
							node = nodes.SelectSingleNode(("//attrib/param[pnome=\"shownavbtncat\"]"));
							if(node!=null){
								ds.Tables[0].Columns.Add("shownavbtncat");
								ds.Tables[0].Rows[0]["shownavbtncat"] = node.ChildNodes[1].InnerText;
							}
							node = null;
							node = nodes.SelectSingleNode(("//attrib/param[pnome=\"csstitolocat\"]"));
							if(node!=null){
								ds.Tables[0].Columns.Add("csstitolocat");
								ds.Tables[0].Rows[0]["csstitolocat"] = node.ChildNodes[1].InnerText;
							}
							node = null;
							node = nodes.SelectSingleNode(("//attrib/param[pnome=\"cssdesccat\"]"));
							if(node!=null){
								ds.Tables[0].Columns.Add("cssdesccat");
								ds.Tables[0].Rows[0]["cssdesccat"] = node.ChildNodes[1].InnerText;
							}
							node = null;
							node = nodes.SelectSingleNode(("//attrib/param[pnome=\"cssartcat\"]"));
							if(node!=null){
								ds.Tables[0].Columns.Add("cssartcat");
								ds.Tables[0].Rows[0]["cssartcat"] = node.ChildNodes[1].InnerText;
							}
							node = null;
							node = nodes.SelectSingleNode(("//attrib/param[pnome=\"cssnavbtncat\"]"));
							if(node!=null){
								ds.Tables[0].Columns.Add("cssnavbtncat");
								ds.Tables[0].Rows[0]["cssnavbtncat"] = node.ChildNodes[1].InnerText;
							}

							ds.Tables[0].Columns.Remove("attrib_param");
						} 
						} 
					}
					}
					
					XmlDocument xmlformdata = ds!=null?fda.DataSetToXmlDocument(ds):null;
					if(xmlformdata==null){
	//					HttpContext.Current.Response.Write("xml nullo");
						return;
					}
					
					xmlstring = xmlformdata.InnerXml;
					string blocco = "<parametri>Visible=false~</parametri>";
					int indicec = xmlstring.IndexOf("<nome>figliodi</nome>");
					if(indicec>0) {
						int index = xmlstring.IndexOf("</valore>",indicec)+9;
						xmlstring = xmlstring.Insert(index,blocco);
					}
					
					if(ACM.cmsarea08.Users.CurrentUser.Role.Score>100 &&!TradMode && !(RevMode&&IsPublisher&&ConfirmChanges&&Upd_Id!="-1")){
						indicec = 0;
						indicec = xmlstring.IndexOf("<nome>titolo</nome>");
						if(indicec>0) {
							int index = xmlstring.IndexOf("</valore>",indicec)+9;
							xmlstring = xmlstring.Insert(index,blocco);
						}
					}
					
					if(TradMode) {

						query = "SELECT lingua FROM " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable + 
						        " where id='" + _ItemID +"' or tradotto_da='" + _ItemID +"' group by lingua ;";
					//	HttpContext.Current.Response.Write(query);
						DataSet dslingueusate = dclass.Helper_Dataset(query);
						if(dslingueusate!=null && dslingueusate.Tables.Count!=0 && dslingueusate.Tables[0].Rows.Count!=0){
							string valori ="";
							foreach(DataRow dr in dslingueusate.Tables[0].Rows){
								valori += dr[0].ToString() + ",";
							}
							if(valori.EndsWith(","))
								valori = valori.Substring(0,valori.Length-1);
							string parametr = "<parametri>ExcludedLang={0}~";
							if(!TradMode) {
								parametr +="Visible=false~";
							}
							parametr += "</parametri>";
							
//							Response.Write(HttpUtility.HtmlEncode(xmlstring));
							int stindex = xmlstring.IndexOf("<nome>lingua</nome>");
							if(stindex>0){
								int index = xmlstring.IndexOf("</valore>",stindex)+9;
								xmlstring = xmlstring.Insert(index,string.Format(parametr,valori));
							}
						}
					} else{
					        
							indicec=0;
							indicec = xmlstring.IndexOf("<nome>lingua</nome>");
							if(indicec>0) {
								int index = xmlstring.IndexOf("</valore>",indicec)+9;
								xmlstring = xmlstring.Insert(index,blocco);
							}
						
					}
					//Response.Write("SONO IO :" + HttpUtility.HtmlEncode(xmlstring));
					if(!string.IsNullOrEmpty(xmlstring))
						nsfOggettoForm.FormData = xmlstring;
					else
						nsfOggettoForm.FormData = ds!=null?fda.DataSetToItanData(ds):null;
				}
				if(InsertMode && ACM.cmsarea08.mainconfiguration.MainConf.ModelloLingua==
				   LanguageModel.Single){
						
						xmlstring += "<impostazioni><set><nome>lingua</nome><valore>"+/*ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita+*/
							"</valore><parametri>Visible=false~</parametri></set></impostazioni>";
					nsfOggettoForm.FormData = xmlstring;
				}
				nsfOggettoForm.Footer = string.Format(footer,autore,datains) + (datains==datamod?"":string.Format(footer_ext,autore2,datamod));
					
					
				
				/* fine blocchetto, casomai mettere in questo blocco le stringhe a "" e l'obj a null  */
				
				
				
			esci:	
				//Assegnazione delle Cose alla pulsanteria:
				adm_buttons.SaveFormClicked += new SaveFormEventHandler(EVENTOSALVA);
				
				adm_buttons.NSFormData = nsfOggettoForm;
			}
			//adm_buttons.CaricaLayoutForm();
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
	
		private void Page_Load(object o , EventArgs e) {
			if(TradMode)
				_ItemID = Request.QueryString["idt"]!=null?Request.QueryString["idt"].ToString():"0";
			else
				_ItemID = getValidContentIDF();
			if(!Page.IsPostBack) {
				
			}
		}
		
		private string getParametro(object parameters,string paramName) {
			if(parameters==null) 
				return "-1";
			//get xml document for parameters
				System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
			try {
					string parametri = "";
					if(parameters is string) 
						xdoc.LoadXml( HttpUtility.HtmlDecode(parameters.ToString()) );
					else if (parameters is Byte[]) {
						xdoc.LoadXml( HttpUtility.HtmlDecode(
							System.Text.Encoding.UTF8.GetString( (byte[]) parameters ) ) );
					}
					System.Xml.XmlNode xnode = null;
					xnode = xdoc.SelectSingleNode("//impostazioni/set[nome='"+paramName+"']/valore");
					if(xnode==null)
						return "-1";
					if(xnode.InnerText.Trim()=="")
						return "-1";
					else
						return xnode.InnerText.Trim();
				} catch (Exception ex) {
					Response.Write(ex.ToString());
					return "-1";
			}
		}
		public void EVENTOSALVA(object o, SaveFormEventArgs e) {
			//devo salvare.
			// e.FormData
			// e.CommandType
			ACM.cmsarea08.Function.TextClass tclass = new ACM.cmsarea08.Function.TextClass();
			string query1 = "";
			string query2 = "";
			string attrib_param="";
//			if(e.CommandType==ACM.cmsarea08.CommandTypes.Insert)
//				if(TradMode)
//					query1 = "insert into {0} (titolo, descrizione, tipo, figliodi,data_mod,data_ins,attrib_param,thumb,lingua,autore,tradotto_da) values " +
//					"('{1}','{2}','C','{3}',Now(),Now(),'{4}','{5}','{6}','" + ACM.cmsarea08.Users.CurrentUser.IdUtente + "','"+ _ItemID +"')  ;";
//				else
//					query1 = "insert into {0} (titolo, descrizione, tipo, figliodi, data_mod, data_ins, attrib_param,thumb,lingua,autore) " +
//					"values ('{1}','{2}','C','{3}',Now(),Now(),'{4}','{5}','{6}','" + ACM.cmsarea08.Users.CurrentUser.IdUtente + "') ;";
//			else if(e.CommandType==ACM.cmsarea08.CommandTypes.Update){
//						
//				query1 = "update {0} set autore='" + ACM.cmsarea08.Users.CurrentUser.IdUtente + "', titolo='{1}', descrizione='{2}',figliodi={3}, data_mod=Now(), attrib_param='{4}', thumb='{5}', lingua='{6}' where id='"+ _ItemID +"' limit 1 ;";
//				query2 = "update " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + "contenuti set sez_id='{0}' where cat_id='"+ _ItemID +"' ;";
//			}
			//Response.Write("DOVREI FARE QUALCOSA: " + e.CommandType + "<br>");
			if(!this.InsertMode && _ItemID == "0"){
					this.PrintMessage(rm.GetString("error_querystring"));
					return;
				}
			XmlDocument xdoc = new XmlDocument();
			if(e.FormData!=null) {
				FormDataAdapter fda = new FormDataAdapter();
				xdoc = fda.ObjectToXmlDocument(e.FormData);
				if(xdoc==null) {
					//Response.Write("no data");
					return;
				}
				XmlNode node;
				bool test = false;
				node = xdoc.DocumentElement;
				string nodoAttribParams = "<attrib>";
				string parames="";
				string paramStessaPagina="";
				
				string forse="";
				string mitico="";
				string thumb = "";
				if(node.SelectSingleNode("//impostazioni/set[nome=\"showtitlecat\"]")== null){
					return;
				}
				
				if(node.SelectSingleNode("//impostazioni/set[nome=\"showtitlecat\"]").ChildNodes.Count>=2){
					forse=node.SelectSingleNode("//impostazioni/set[nome=\"showtitlecat\"]").ChildNodes[1].InnerText;
					if(forse.Trim() !="")
						parames += "<param><pnome>showtitlecat</pnome><pvalore><![CDATA[" + forse + "]]></pvalore></param>";
					mitico=forse;
					forse="";
				}
				if(node.SelectSingleNode("//impostazioni/set[nome=\"showdesccat\"]")== null){
					return;
				}
				
				if(node.SelectSingleNode("//impostazioni/set[nome=\"showdesccat\"]").ChildNodes.Count>=2){
					forse=node.SelectSingleNode("//impostazioni/set[nome=\"showdesccat\"]").ChildNodes[1].InnerText;
					if(forse.Trim() !="")
						parames += "<param><pnome>showdesccat</pnome><pvalore><![CDATA[" + forse + "]]></pvalore></param>";
					mitico=forse;
					forse="";
				}
				if(node.SelectSingleNode("//impostazioni/set[nome=\"showartcat\"]")== null){
					return;
				}
				
				if(node.SelectSingleNode("//impostazioni/set[nome=\"showartcat\"]").ChildNodes.Count>=2){
					forse=node.SelectSingleNode("//impostazioni/set[nome=\"showartcat\"]").ChildNodes[1].InnerText;
					if(forse.Trim() !="")
						parames += "<param><pnome>showartcat</pnome><pvalore><![CDATA[" + forse + "]]></pvalore></param>";
					mitico=forse;
					forse="";
				}
				if(node.SelectSingleNode("//impostazioni/set[nome=\"shownavbtncat\"]")== null){
					return;
				}
				
				if(node.SelectSingleNode("//impostazioni/set[nome=\"shownavbtncat\"]").ChildNodes.Count>=2){
					forse=node.SelectSingleNode("//impostazioni/set[nome=\"shownavbtncat\"]").ChildNodes[1].InnerText;
					if(forse.Trim() !="")
						parames += "<param><pnome>shownavbtncat</pnome><pvalore><![CDATA[" + forse + "]]></pvalore></param>";
					mitico=forse;
					forse="";
				}
				if(node.SelectSingleNode("//impostazioni/set[nome=\"csstitolocat\"]")== null){
					return;
				}
				
				if(node.SelectSingleNode("//impostazioni/set[nome=\"csstitolocat\"]").ChildNodes.Count>=2){
					forse=node.SelectSingleNode("//impostazioni/set[nome=\"csstitolocat\"]").ChildNodes[1].InnerText;
					if(forse.Trim() !="")
						parames += "<param><pnome>csstitolocat</pnome><pvalore><![CDATA[" + forse + "]]></pvalore></param>";
					mitico=forse;
					forse="";
				}
				if(node.SelectSingleNode("//impostazioni/set[nome=\"cssartcat\"]")== null){
					return;
				}
				
				if(node.SelectSingleNode("//impostazioni/set[nome=\"cssartcat\"]").ChildNodes.Count>=2){
					forse=node.SelectSingleNode("//impostazioni/set[nome=\"cssartcat\"]").ChildNodes[1].InnerText;
					if(forse.Trim() !="")
						parames += "<param><pnome>cssartcat</pnome><pvalore><![CDATA[" + forse + "]]></pvalore></param>";
					mitico=forse;
					forse="";
				}
				if(node.SelectSingleNode("//impostazioni/set[nome=\"cssnavbtncat\"]")== null){
					return;
				}
				
				if(node.SelectSingleNode("//impostazioni/set[nome=\"cssnavbtncat\"]").ChildNodes.Count>=2){
					forse=node.SelectSingleNode("//impostazioni/set[nome=\"cssnavbtncat\"]").ChildNodes[1].InnerText;
					if(forse.Trim() !="")
						parames += "<param><pnome>cssnavbtncat</pnome><pvalore><![CDATA[" + forse + "]]></pvalore></param>";
					mitico=forse;
					forse="";
				}
				if(node.SelectSingleNode("//impostazioni/set[nome=\"cssdesccat\"]")== null){
					return;
				}
				
				if(node.SelectSingleNode("//impostazioni/set[nome=\"cssdesccat\"]").ChildNodes.Count>=2){
					
					
					//return;
			//	Response.Write(capro.ChildNodes[1].InnerText + " -- ");
					forse=node.SelectSingleNode("//impostazioni/set[nome=\"cssdesccat\"]").ChildNodes[1].InnerText;
				parames += "<param><pnome>cssdesccat</pnome><pvalore><![CDATA[" + forse + "]]></pvalore></param>";
					mitico+=forse;
					forse="";
				}
				
				//carico la thumb img
				if(node.SelectSingleNode("//impostazioni/set[nome=\"thumbimg\"]")!=null){
					thumb  = node.SelectSingleNode("//impostazioni/set[nome=\"thumbimg\"]").ChildNodes[1].InnerText;
				}					
				
				if(parames!=""){
						nodoAttribParams += (parames + "</attrib>");
						
						nodoAttribParams = fda.Compress(nodoAttribParams);
						
						
				} 
				//Response.Write("MA VACCA TROIA");
				
				node=null;
				node = xdoc.DocumentElement;
				string nodoTitolo = "";
				XmlNode capro = node.SelectSingleNode("//impostazioni/set[nome=\"titolo\"]");
//				if(capro!=null)
					nodoTitolo = capro.ChildNodes[1].InnerText;
					
				string nodoLingua = "";
				capro = node.SelectSingleNode("//impostazioni/set[nome=\"lingua\"]");
				if(capro!=null)
					nodoLingua = capro.ChildNodes[1].InnerText;
				capro=null;
				
				string nodoSezione = "";
				capro = node.SelectSingleNode("//impostazioni/set[nome=\"figliodi\"]");
				if(capro!=null){
					if(capro.ChildNodes[1].InnerText.Trim()=="-1"){
						PrintMessage(rm.GetString("error_sez"));
						return;
					}
				
					nodoSezione = capro.ChildNodes[1].InnerText;
				}
				capro=null;
				
				object obj=null;
				if(nodoTitolo.Trim()!="")
					obj = dclass.HStandard_SC("select count(*) from "+ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle+DBActionTable+
					                          " where titolo='"+tclass.SqlTesto(nodoTitolo)+"' and tipo='C' " +
					                          "and lingua='" + nodoLingua + "' and figliodi='" + nodoSezione + "' ;");
				if(!InsertMode || obj!=null && obj.ToString()=="0"){
				
				
					
				capro=null;
				string nodoDescrizione = "";
				capro = node.SelectSingleNode("//impostazioni/set[nome=\"descrizione\"]");
				if(capro!=null)
					nodoDescrizione = capro.ChildNodes[1].InnerText;
				capro=null;
				
				
				string nodoAutore = ACM.cmsarea08.Users.CurrentUser.IdUtente;
//				query1 = string.Format(query1,ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable,
//				                      tclass.SqlTesto(nodoTitolo),tclass.SqlTesto(nodoDescrizione),
//				                      tclass.SqlTesto(nodoSezione),tclass.SqlTestoBlob(nodoAttribParams),tclass.SqlTestoBlob(thumb),
//				                     tclass.SqlTestoBlob(nodoLingua));
//				
//				query2 = string.Format(query2,tclass.SqlTesto(nodoSezione));
				string query = "";
//				Response.Write("inizio a verificare: e.CommandType=\""+e.CommandType.ToString()+"\" ConfirmChanges=\"" + ConfirmChanges.ToString()+
//				               "\" IsPublisher=\"" + IsPublisher.ToString() + "\" RevMode=\"" + RevMode.ToString() + "\" Upd_Id=\"" + Upd_Id + "\"");
				if(e.CommandType==ACM.cmsarea08.CommandTypes.Insert || 
					   RevMode && !IsPublisher && deleting!="N" ){
					if(TradMode){
						
						query = string.Format(trad_query,ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable,
				                      tclass.SqlTesto(nodoTitolo),
				                      tclass.SqlTesto(nodoDescrizione),
				                      tclass.SqlTesto(nodoSezione),
				                      tclass.SqlTestoBlob(nodoAttribParams),
				                      tclass.SqlTestoBlob(thumb),
				                      tclass.SqlTesto(nodoLingua),
				                      tclass.SqlTesto(nodoAutore),
									  this._ItemID,
									  ((!RevMode || IsPublisher)?"1":"0"),
									  ((!RevMode || IsPublisher)?"0":"N"));
						int reso = 0;
						try{
							reso = dclass.ExecuteScalar(query);
						
							if(reso<1)
								this.PrintMessage(rm.GetString("error_db"));
							else{
								this.PrintMessage(rm.GetString("success_tra_cat"));
								
							}
								
						}
						catch(MySql.Data.MySqlClient.MySqlException ex){
							this.PrintMessage(rm.GetString("error_db"));
							Response.Write("<hr>" + ex.ToString());
						}
					}
					else{
						datains = datains=="-"?System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"):datains;
						query = string.Format(insert_query,ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable,
				                      tclass.SqlTesto(nodoTitolo),
				                      tclass.SqlTesto(nodoDescrizione),
				                      tclass.SqlTesto(nodoSezione),
				                      tclass.SqlTestoBlob(nodoAttribParams),
				                      tclass.SqlTestoBlob(thumb),
				                      tclass.SqlTesto(nodoLingua),
				                      tclass.SqlTesto(nodoAutore),
				                      ((RevMode && !IsPublisher && !this.InsertMode)?this._ItemID:Upd_Id),
									  (!RevMode || IsPublisher)?"1":"0",
										((RevMode && !IsPublisher)?"N":"0"), //deleting
									  	((RevMode && !IsPublisher && !InsertMode)?_AutoreID:tclass.SqlTesto(nodoAutore)), //autore
									  	((RevMode && !IsPublisher)?"'"+datains+"'":"Now()")); //datains;
						int reso = 0;
						try{
							reso = dclass.ExecuteScalar(query);
						
							if(reso<1)
								this.PrintMessage(rm.GetString("error_db"));
							else{
								this.PrintMessage(rm.GetString("success_ins_cat"));
								
							}
								
						}
						catch(MySql.Data.MySqlClient.MySqlException ex){
							this.PrintMessage(rm.GetString("error_db"));
							Response.Write("<hr>" + ex.ToString());
						}
					}
				}else if(e.CommandType==ACM.cmsarea08.CommandTypes.Update){
					
					
					query = string.Format(update_query,ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable,
				                      tclass.SqlTesto(nodoTitolo),
				                      tclass.SqlTesto(nodoDescrizione),
				                      tclass.SqlTesto(nodoSezione),
				                      tclass.SqlTestoBlob(nodoAttribParams),
				                      tclass.SqlTestoBlob(thumb),
				                      tclass.SqlTesto(nodoLingua),
				                      (RevMode && this.ConfirmChanges?_Autore2ID:tclass.SqlTesto(nodoAutore)),
				                      ((RevMode && IsPublisher && Upd_Id!="-1")?Upd_Id:this._ItemID),
				                      ((RevMode && !IsPublisher)?"N":"0"));
						int reso = 0;
						try{
							reso = dclass.ExecuteScalar(query);
						
							if(reso<1)
								this.PrintMessage(rm.GetString("error_db"));
							else{
								this.PrintMessage(rm.GetString("success_upd_cat"));
								if(RevMode&&IsPublisher&&ConfirmChanges&&Upd_Id!="-1"){
									reso += dclass.ExecuteScalar("delete from " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle+
									                             DBActionTable + " where id = '" +_ItemID +"' ;");
								}
							}
							
						}
						catch(MySql.Data.MySqlClient.MySqlException ex){
							this.PrintMessage(rm.GetString("error_db"));
							Response.Write("<hr>" + ex.ToString());
						}
					
					
					
					
					
					
				}
				}else{
					if(nodoTitolo.Trim()=="")
						this.PrintMessage(rm.GetString("error_invalid_data"));
					else
					this.PrintMessage(rm.GetString("error_same_name"));
				}
				
 				
				
			}
			//this.PrintMessage("formdata null");
			
			
			//quando devi stampare qualcosa:
			//this.PrintMessage("MESSAGGIO");
		}
		
		
	}
	
}
